package com.taotao.portal.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.portal.pojo.CartItem;
import com.taotao.rest.webservice.Item;
import com.taotao.utils.CookieUtils;
import com.taotao.utils.JsonUtils;
@Service
public class CartServiceImpl implements CartService {
	@Autowired
	private ItemService itemService;
	@Override
	public TaotaoResult add(HttpServletRequest request, HttpServletResponse response, long id, Integer num) {
		CartItem cartItem = null;
		List<CartItem> itemList = getCartList(request);
		for (CartItem cItem : itemList) {
			if (cItem.getId() == id) {
				cItem.setNum(cItem.getNum() + num);
				cartItem = cItem;
				break;
			}
		}
		
		if (cartItem == null) {
			cartItem = new CartItem();
			Item item = itemService.getItemBaseInfo(id);
			if (item != null) {
				cartItem.setId(Long.parseLong(item.getId()));
				cartItem.setImage(item.getImage() == null ? "":item.getImage().split(",")[0]);
				cartItem.setNum(num);
				cartItem.setPrice(item.getPrice());
				cartItem.setTitle(item.getTitle());
			}
			itemList.add(cartItem);
		}
		CookieUtils.setCookie(request, response, "TT_CART", JsonUtils.objectToJson(itemList));
		return TaotaoResult.ok();
	}

	private List<CartItem> getCartList(HttpServletRequest request) {
		String cookies = CookieUtils.getCookieValue(request, "TT_CART", true);
		if (cookies == null) {
			return new ArrayList<>();
		}
		try {
			List<CartItem> items = JsonUtils.jsonToList(cookies, CartItem.class);
			return items;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ArrayList<>();
	}

	@Override
	public List<CartItem> getCartItemList(HttpServletRequest request, HttpServletResponse response) {
		List<CartItem> itemList = getCartList(request);
		return itemList;
	}

	@Override
	public TaotaoResult updateNum(long itemId, Integer num, HttpServletRequest request, HttpServletResponse response) {
		List<CartItem> list = getCartList(request);
		CartItem c=null;
		for (int i=0;i<list.size();i++) {
			if (( c= list.get(i)).getId() == itemId) {
				c.setNum(num);
				list.set(i, c);
				break;
			}
		}
		CookieUtils.setCookie(request, response, "TT_CART", JsonUtils.objectToJson(list));
		return TaotaoResult.ok();
	}

	@Override
	public TaotaoResult delete(long id, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		List<CartItem> list = getCartList(request);
		for (CartItem item : list) {
			if (item.getId() == id) {
				list.remove(item);
				break;
			}
		}
		CookieUtils.setCookie(request, response, "TT_CART", JsonUtils.objectToJson(list));
		return TaotaoResult.ok();
	}
}
